package Test04;

/*
（2）拓展任务：设一循环队列Queue，只有头指针front，不设尾指针，
另设一个内含元素个数的计数器，试写出相应的进队、出队算法。
*/
public class SequenceQueue2<T> {
    final int MAX_CAPACITY = 10;
    private T queueArray[];
    private int front, size;

    public SequenceQueue2() {
        front = size = 0;
        queueArray = (T[]) new Object[this.MAX_CAPACITY];
    }

    public void enQueue(T obj) {
        if (size == queueArray.length - 1) {
            T[] p = (T[]) new Object[queueArray.length * 2];
            if (front == 0) {
                for (int i = 1; i <= size; i++) {
                    p[i] = queueArray[i];
                }
            } else {
                int i, j = 1;
                for (i = front + 1; i < queueArray.length; i++, j++) {
                    p[j] = queueArray[i];
                }
                for (i = 0; i <= (size + front) % queueArray.length; i++, j++) {
                    p[j] = queueArray[i];
                }
                front = 0;
            }
            queueArray = p;
        }
        size++;
        queueArray[(size + front) % queueArray.length] = obj;
    }

    public T deQueue() {
        if (isEmpty()) {
            System.out.println("队列已空,无法出队!");
            return null;
        }
        front = (front + 1) % queueArray.length;
        size--;
        return queueArray[front];
    }

    public T getHead() {
        if (isEmpty()) {
            System.out.println("队列已空,无法读取元素!");
            return null;
        }
        return queueArray[(front + 1) % queueArray.length];
    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void nextOrder() {
        System.out.println("队列元素为:" + toString());
    }

    @Override
    public String toString() {
        String s = "";
        int i, j = front;
        for (i = 1; i < size; i++) {
            j = (j + 1) % queueArray.length;
            s += queueArray[(front + 1 + i) % queueArray.length] + "\t";
        }
        return s;
    }

    public void clear() {
        front = size = 0;
    }
}